package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.mat.ipaas.ucenter.service.api.system.SysCategoryRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysCategoryDTO;
import org.mat.ipaas.ucenter.service.dto.system.model.TreeSelectModelDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.DictModelDTO;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.util.SessionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.system.vo.DictModel;
import org.mat.ipaas.ucenter.biz.common.util.ImportExcelUtil;
import org.mat.ipaas.ucenter.biz.common.util.SqlInjectionUtil;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysCategory;
import org.mat.ipaas.ucenter.biz.modules.system.model.TreeSelectModel;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysCategoryService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分类字典
 */
@RestController
@RequestMapping("/sys/category")
@Slf4j
public class SysCategoryController implements SysCategoryRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysCategoryService sysCategoryService;

    /**
     * 分类编码0
     */
    private static final String CATEGORY_ROOT_CODE = "0";

    /**
     * 分页列表查询
     *
     * @param sysCategoryDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/rootList")
    public MatApiResponse<Page<SysCategoryDTO>> queryPageList(@SpringQueryMap SysCategoryDTO sysCategoryDTO,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysCategory sysCategory = toSysCategory(sysCategoryDTO);

        if (oConvertUtils.isEmpty(sysCategory.getPid())) {
            sysCategory.setPid("0");
        }
        MatApiResponse<Page<SysCategoryDTO>> matApiResponse = new MatApiResponse<>();
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------

        //--author:os_chengtgen---date:20190804 -----for: 分类字典页面显示错误,issues:377--------start
        //--author:liusq---date:20211119 -----for: 【vue3】分类字典页面查询条件配置--------start
        QueryWrapper<SysCategory> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
        String name = sysCategory.getName();
        String code = sysCategory.getCode();
        //QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<SysCategory>();
        if (StringUtils.isBlank(name) && StringUtils.isBlank(code)) {
            queryWrapper.eq("pid", sysCategory.getPid());
        }
        //--author:liusq---date:20211119 -----for: 分类字典页面查询条件配置--------end
        //--author:os_chengtgen---date:20190804 -----for:【vue3】 分类字典页面显示错误,issues:377--------end

        Page<SysCategory> page = new Page<SysCategory>(pageNo, pageSize);
        IPage<SysCategory> pageList = sysCategoryService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysCategoryDTOPage(pageList));
        return matApiResponse;
    }


    @GetMapping(value = "/childList")
    public MatApiResponse<List<SysCategoryDTO>> queryPageList(@SpringQueryMap SysCategoryDTO sysCategoryDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysCategory sysCategory = toSysCategory(sysCategoryDTO);

        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------
        MatApiResponse<List<SysCategoryDTO>> matApiResponse = new MatApiResponse<>();
        QueryWrapper<SysCategory> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
        List<SysCategory> list = sysCategoryService.list(queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysCategoryDTOList(list));
        return matApiResponse;
    }


    /**
     * 添加
     *
     * @param sysCategoryDTO
     * @return
     */
    @PostMapping(value = "/add")
    public MatApiResponse<SysCategoryDTO> add(@RequestBody SysCategoryDTO sysCategoryDTO) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse<>();
        SysCategory sysCategory = toSysCategory(sysCategoryDTO);

        try {
            sysCategoryService.addSysCategory(sysCategory);
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param sysCategoryDTO
     * @return
     */
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysCategoryDTO> edit(@RequestBody SysCategoryDTO sysCategoryDTO) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse<>();
        SysCategory sysCategory = toSysCategory(sysCategoryDTO);

        SysCategory sysCategoryEntity = sysCategoryService.getById(sysCategory.getId());
        if (sysCategoryEntity == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            sysCategoryService.updateSysCategory(sysCategory);
            matApiResponse.success("修改成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public MatApiResponse<SysCategoryDTO> delete(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse<>();
        SysCategory sysCategory = sysCategoryService.getById(id);
        if (sysCategory == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            this.sysCategoryService.deleteSysCategory(id);
            matApiResponse.success("删除成功!");
        }

        return matApiResponse;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<SysCategoryDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse<>();
        if (ids == null || "".equals(ids.trim())) {
            matApiResponse.fail("参数不识别！");
        } else {
            this.sysCategoryService.deleteSysCategory(ids);
            matApiResponse.success("删除成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public MatApiResponse<SysCategoryDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse<>();
        SysCategory sysCategory = sysCategoryService.getById(id);
        if (sysCategory == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysCategoryDTO(sysCategory));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysCategoryDTO sysCategoryDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysCategory sysCategory = toSysCategory(sysCategoryDTO);

        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            sysCategory.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------

        // Step.1 组装查询条件查询数据
        QueryWrapper<SysCategory> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, request.getParameterMap());
        List<SysCategory> pageList = sysCategoryService.list(queryWrapper);
        // Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isEmpty(selections)) {
            mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            List<SysCategory> exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
            mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "分类字典列表");
        mv.addObject(NormalExcelConstants.CLASS, SysCategory.class);
        LoginUserDTO user = sessionService.getLoginUser();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分类字典列表数据", "导出人:" + user.getRealname(), "导出信息"));
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysCategory> listSysCategorys = ExcelImportUtil.importExcel(file.getInputStream(), SysCategory.class, params);
                //按照编码长度排序
                Collections.sort(listSysCategorys);
                log.info("排序后的list====>", listSysCategorys);
                for (int i = 0; i < listSysCategorys.size(); i++) {
                    SysCategory sysCategoryExcel = listSysCategorys.get(i);
                    String code = sysCategoryExcel.getCode();
                    if (code.length() > 3) {
                        String pCode = sysCategoryExcel.getCode().substring(0, code.length() - 3);
                        log.info("pCode====>", pCode);
                        String pId = sysCategoryService.queryIdByCode(pCode);
                        log.info("pId====>", pId);
                        if (StringUtils.isNotBlank(pId)) {
                            sysCategoryExcel.setPid(pId);
                        }
                    } else {
                        sysCategoryExcel.setPid("0");
                    }
                    try {
                        sysCategoryService.save(sysCategoryExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage().toLowerCase();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_UNIQ_CATEGORY_CODE)) {
                            errorMessage.add("第 " + lineNumber + " 行：分类编码已经存在，忽略导入。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }


    /**
     * 加载单个数据 用于回显
     */
    @RequestMapping(value = "/loadOne", method = RequestMethod.GET)
    public MatApiResponse<SysCategoryDTO> loadOne(@RequestParam(name = "field") String field, @RequestParam(name = "val") String val) {
        MatApiResponse<SysCategoryDTO> matApiResponse = new MatApiResponse();
        try {
            //update-begin-author:taoyan date:2022-5-6 for: issues/3663 sql注入问题
            boolean isClassField = SqlInjectionUtil.isClassField(field, SysCategory.class);
            if (!isClassField) {
                return MatApiResponse.fail("字段无效，请检查!");
            }
            //update-end-author:taoyan date:2022-5-6 for: issues/3663 sql注入问题
            QueryWrapper<SysCategory> query = new QueryWrapper<SysCategory>();
            query.eq(field, val);
            List<SysCategory> ls = this.sysCategoryService.list(query);
            if (ls == null || ls.size() == 0) {
                matApiResponse.setMessage("查询无果");
                matApiResponse.setSuccess(false);
            } else if (ls.size() > 1) {
                matApiResponse.setMessage("查询数据异常,[" + field + "]存在多个值:" + val);
                matApiResponse.setSuccess(false);
            } else {
                matApiResponse.setSuccess(true);
                matApiResponse.setData(toSysCategoryDTO(ls.get(0)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            matApiResponse.setMessage(e.getMessage());
            matApiResponse.setSuccess(false);
        }
        return matApiResponse;
    }

    /**
     * 加载节点的子数据
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public MatApiResponse<List<TreeSelectModelDTO>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        MatApiResponse<List<TreeSelectModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            List<TreeSelectModel> ls = this.sysCategoryService.queryListByPid(pid);
            matApiResponse.setData(toTreeSelectModelDTOList(ls));
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            matApiResponse.setMessage(e.getMessage());
            matApiResponse.setSuccess(false);
        }
        return matApiResponse;
    }

    /**
     * 加载一级节点/如果是同步 则所有数据
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public MatApiResponse<List<TreeSelectModelDTO>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        MatApiResponse<List<TreeSelectModelDTO>> matApiResponse = new MatApiResponse<>();
        try {
            List<TreeSelectModel> ls = this.sysCategoryService.queryListByCode(pcode);
            if (!async) {
                loadAllCategoryChildren(ls);
            }
            matApiResponse.setData(toTreeSelectModelDTOList(ls));
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            matApiResponse.setMessage(e.getMessage());
            matApiResponse.setSuccess(false);
        }
        return matApiResponse;
    }

    /**
     * 递归求子节点 同步加载用到
     */
    private void loadAllCategoryChildren(List<TreeSelectModel> ls) {
        for (TreeSelectModel tsm : ls) {
            List<TreeSelectModel> temp = this.sysCategoryService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllCategoryChildren(temp);
            }
        }
    }

    /**
     * 校验编码
     *
     * @param pid
     * @param code
     * @return
     */
    @GetMapping(value = "/checkCode")
    public MatApiResponse<?> checkCode(@RequestParam(name = "pid", required = false) String pid, @RequestParam(name = "code", required = false) String code) {
        if (oConvertUtils.isEmpty(code)) {
            return MatApiResponse.fail("错误,类型编码为空!");
        }
        if (oConvertUtils.isEmpty(pid)) {
            return MatApiResponse.success();
        }
        SysCategory parent = this.sysCategoryService.getById(pid);
        if (code.startsWith(parent.getCode())) {
            return MatApiResponse.success();
        } else {
            return MatApiResponse.fail("编码不符合规范,须以\"" + parent.getCode() + "\"开头!");
        }

    }


    /**
     * 分类字典树控件 加载节点
     *
     * @param pid
     * @param pcode
     * @param condition
     * @return
     */
    @RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
    public MatApiResponse<List<TreeSelectModelDTO>> loadDict(@RequestParam(name = "pid", required = false) String pid, @RequestParam(name = "pcode", required = false) String pcode, @RequestParam(name = "condition", required = false) String condition) {
        MatApiResponse<List<TreeSelectModelDTO>> matApiResponse = new MatApiResponse<>();
        //pid如果传值了 就忽略pcode的作用
        if (oConvertUtils.isEmpty(pid)) {
            if (oConvertUtils.isEmpty(pcode)) {
                matApiResponse.setSuccess(false);
                matApiResponse.setMessage("加载分类字典树参数有误.[null]!");
                return matApiResponse;
            } else {
                if (ISysCategoryService.ROOT_PID_VALUE.equals(pcode)) {
                    pid = ISysCategoryService.ROOT_PID_VALUE;
                } else {
                    pid = this.sysCategoryService.queryIdByCode(pcode);
                }
                if (oConvertUtils.isEmpty(pid)) {
                    matApiResponse.setSuccess(false);
                    matApiResponse.setMessage("加载分类字典树参数有误.[code]!");
                    return matApiResponse;
                }
            }
        }
        Map<String, String> query = null;
        if (oConvertUtils.isNotEmpty(condition)) {
            query = JSON.parseObject(condition, Map.class);
        }
        List<TreeSelectModel> ls = sysCategoryService.queryListByPid(pid, query);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toTreeSelectModelDTOList(ls));
        return matApiResponse;
    }

    /**
     * 分类字典控件数据回显[表单页面]
     *
     * @param ids
     * @param delNotExist 是否移除不存在的项，默认为true，设为false如果某个key不存在数据库中，则直接返回key本身
     * @return
     */
    @RequestMapping(value = "/loadDictItem", method = RequestMethod.GET)
    public MatApiResponse<List<String>> loadDictItem(@RequestParam(name = "ids") String ids, @RequestParam(name = "delNotExist", required = false, defaultValue = "true") boolean delNotExist) {
        MatApiResponse<List<String>> matApiResponse = new MatApiResponse<>();
        // 非空判断
        if (StringUtils.isBlank(ids)) {
            matApiResponse.setSuccess(false);
            matApiResponse.setMessage("ids 不能为空");
            return matApiResponse;
        }
        // 查询数据
        List<String> textList = sysCategoryService.loadDictItem(ids, delNotExist);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(textList);
        return matApiResponse;
    }

    /**
     * [列表页面]加载分类字典数据 用于值的替换
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/loadAllData", method = RequestMethod.GET)
    public MatApiResponse<List<DictModelDTO>> loadAllData(@RequestParam(name = "code", required = true) String code) {
        MatApiResponse<List<DictModelDTO>> matApiResponse = new MatApiResponse<>();

        LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>();
        if (oConvertUtils.isNotEmpty(code) && !CATEGORY_ROOT_CODE.equals(code)) {
            query.likeRight(SysCategory::getCode, code);
        }
        List<SysCategory> list = this.sysCategoryService.list(query);
        if (list == null || list.size() == 0) {
            matApiResponse.setMessage("无数据,参数有误.[code]");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
        List<DictModel> rdList = new ArrayList<DictModel>();
        for (SysCategory c : list) {
            rdList.add(new DictModel(c.getId(), c.getName()));
        }
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toDictModelDTOList(rdList));
        return matApiResponse;
    }


    /**
     * 根据父级id批量查询子节点
     *
     * @param parentIds
     * @return
     */
    @GetMapping("/getChildListBatch")
    public MatApiResponse getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<SysCategory> list = sysCategoryService.list(queryWrapper);
            IPage<SysCategory> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return MatApiResponse.success(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return MatApiResponse.fail("批量查询子节点失败：" + e.getMessage());
        }
    }


    private List<SysCategoryDTO> toSysCategoryDTOList(List<SysCategory> list) {
        List<SysCategoryDTO> sysCategoryDTOList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(list)) {
            for (SysCategory sysCategory : list) {
                sysCategoryDTOList.add(toSysCategoryDTO(sysCategory));
            }
        }
        return sysCategoryDTOList;
    }


    private Page<SysCategoryDTO> toSysCategoryDTOPage(IPage<SysCategory> pageList) {
        Page<SysCategoryDTO> sysCategoryDTOPage = new Page<>();
        List<SysCategoryDTO> sysCategoryDTOList = new ArrayList<>();

        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysCategory sysCategory : pageList.getRecords()) {
                sysCategoryDTOList.add(toSysCategoryDTO(sysCategory));
            }
        }

        sysCategoryDTOPage.setTotal(pageList.getTotal());
        sysCategoryDTOPage.setSize(pageList.getSize());
        sysCategoryDTOPage.setCurrent(pageList.getCurrent());
        sysCategoryDTOPage.setRecords(sysCategoryDTOList);
        return sysCategoryDTOPage;
    }

    private SysCategoryDTO toSysCategoryDTO(SysCategory sysCategory) {
        if (sysCategory == null) {
            return null;
        }
        SysCategoryDTO sysCategoryDTO = new SysCategoryDTO();
        sysCategoryDTO.setId(sysCategory.getId());
        sysCategoryDTO.setPid(sysCategory.getPid());
        sysCategoryDTO.setName(sysCategory.getName());
        sysCategoryDTO.setCode(sysCategory.getCode());
        sysCategoryDTO.setCreateBy(sysCategory.getCreateBy());
        sysCategoryDTO.setCreateTime(sysCategory.getCreateTime());
        sysCategoryDTO.setUpdateBy(sysCategory.getUpdateBy());
        sysCategoryDTO.setUpdateTime(sysCategory.getUpdateTime());
        sysCategoryDTO.setSysOrgCode(sysCategory.getSysOrgCode());
        sysCategoryDTO.setHasChild(sysCategory.getHasChild());
        sysCategoryDTO.setTenantId(sysCategory.getTenantId());
        return sysCategoryDTO;
    }

    private SysCategory toSysCategory(SysCategoryDTO sysCategoryDTO) {
        if (sysCategoryDTO == null) {
            return null;
        }
        SysCategory sysCategory = new SysCategory();
        sysCategory.setId(sysCategoryDTO.getId());
        sysCategory.setPid(sysCategoryDTO.getPid());
        sysCategory.setName(sysCategoryDTO.getName());
        sysCategory.setCode(sysCategoryDTO.getCode());
        sysCategory.setCreateBy(sysCategoryDTO.getCreateBy());
        sysCategory.setCreateTime(sysCategoryDTO.getCreateTime());
        sysCategory.setUpdateBy(sysCategoryDTO.getUpdateBy());
        sysCategory.setUpdateTime(sysCategoryDTO.getUpdateTime());
        sysCategory.setSysOrgCode(sysCategoryDTO.getSysOrgCode());
        sysCategory.setHasChild(sysCategoryDTO.getHasChild());
        sysCategory.setTenantId(sysCategoryDTO.getTenantId());
        return sysCategory;
    }


    private List<TreeSelectModelDTO> toTreeSelectModelDTOList(List<TreeSelectModel> ls) {
        List<TreeSelectModelDTO> treeSelectModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ls)) {
            for (TreeSelectModel treeSelectModel : ls) {
                treeSelectModelDTOList.add(toTreeSelectModelDTO(treeSelectModel));
            }
        }

        return treeSelectModelDTOList;
    }

    private TreeSelectModelDTO toTreeSelectModelDTO(TreeSelectModel treeSelectModel) {
        if (treeSelectModel == null) {
            return null;
        }
        TreeSelectModelDTO treeSelectModelDTO = new TreeSelectModelDTO();
        treeSelectModelDTO.setKey(treeSelectModel.getKey());
        treeSelectModelDTO.setTitle(treeSelectModel.getTitle());
        treeSelectModelDTO.setLeaf(treeSelectModel.isLeaf());
        treeSelectModelDTO.setIcon(treeSelectModel.getIcon());
        treeSelectModelDTO.setParentId(treeSelectModel.getParentId());
        treeSelectModelDTO.setValue(treeSelectModel.getValue());
        treeSelectModelDTO.setCode(treeSelectModel.getCode());
        //TODO 这里有递归逻辑，重点看下代码
        treeSelectModelDTO.setChildren(toTreeSelectModelDTOList(treeSelectModel.getChildren()));
        return treeSelectModelDTO;
    }

    private List<DictModelDTO> toDictModelDTOList(List<DictModel> rdList) {
        List<DictModelDTO> dictModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(rdList)) {
            for (DictModel dictModel : rdList) {
                dictModelDTOList.add(toDictModelDTO(dictModel));
            }
        }
        return dictModelDTOList;
    }

    private DictModelDTO toDictModelDTO(DictModel dictModel) {
        if (dictModel == null) {
            return null;
        }
        DictModelDTO dictModelDTO = new DictModelDTO();
        dictModelDTO.setValue(dictModel.getValue());
        dictModelDTO.setText(dictModel.getText());
        return dictModelDTO;
    }

}
